<?php


namespace app\business\controller;

use app\business\model\SaasGoods;
use app\common\validate\GoodsValidate;
use think\Db;
use think\Request;

class Goods extends Base
{
    public function index(Request $request)
    {
        $crumbs['oneMenuName'] = '商家管理';
        $crumbs['twoMenuName'] = '商品列表';

        $join = [
            ['app_saas_business b','a.b_id=b.id'],
            ['app_goods_type c','a.type_id=c.id'],
        ];

        $search = $request->get('search');
        $map = [];
        $where = [];
        if ($search){
            $where['a.goods_name'] = ['LIKE','%'.$search.'%'];
            $map['query']['search'] = $search;
        }

        $where['b.status'] = 1;

        $data = db('saas_goods')->alias('a')
            ->field('a.*, b.name, c.name type_name')
            ->join($join)
            ->where($where)
            ->paginate(10, false, $map);

        return $this->fetch('', compact('crumbs', 'data'));
    }

    public function add(Request $request)
    {
        if ($request->isPost()){

            $post = $request->post();

            $result = $this->validate($post, 'GoodsValidate');
            if($result !== true){
                $ajax['msg'] = $result;
                return json($ajax);
            }

            $data['goods_name'] = $post['goods_name'];
            $data['img'] = $post['img'];
            $data['type_id'] = $post['type_id'];
            $data['desc'] = $post['desc'];
            $data['b_id'] = $post['b_id'];
            $data['imgs'] = $post['imgs'];
            $data['is_group_buy'] = $post['is_group_buy'];

            Db::startTrans();
            $res = SaasGoods::create($data);
            if ($res->id){


                // 团购数量和规格 转 json
                //$number_num_json = [];
                $specsData = [];
                foreach($post['t_price_number'] as $k1 => $str){

                    //$number_num_arr = [];
                    //$arr = explode('@', $str);
                    //
                    //foreach($arr as $k => $v){
                    //    //$ar = explode(',', $v);
                    //    //$number_num_arr[$ar[0]] = $ar[1];
                    //    $number_num_arr[$k+1] = $v;
                    //
                    //}
                    //
                    //$number_num_json[] = json_encode($number_num_arr);

                    // 存储商品规格数据
                    if ($post['is_group_buy'] == 2){
                        $specsData[] =
                            [
                                'specs_name' => $post['specs_name'][$k1],
                                'stock' => $post['stock'][$k1],
                                //'t_price_number' => $number_num_json[$k1],
                                't_price_number' => $str,
                                'goods_id' => $res->id,
                            ];
                    }else{
                        $specsData[] =
                            [
                                'specs_name' => $post['specs_name'][$k1],
                                'stock' => $post['stock'][$k1],
                                'price' => $post['price'][$k1],
                                //'t_price_number' => $number_num_json[$k1],
                                't_price_number' => $str,
                                'goods_id' => $res->id,
                            ];
                    }
                }

                $addSpecs = db('saas_goods_specs')->insertAll($specsData);
                if ($addSpecs){
                    Db::commit();
                    $ajax['code'] = 1;
                    $ajax['msg'] = '操作成功';
                    $ajax['url'] = url('/admin/goods');
                }else{
                    Db::rollback();
                    $ajax['msg'] = '操作失败';
                }
            }else{
                $ajax['msg'] = '操作失败';
            }
            return json($ajax);

        }else{
            $crumbs['oneMenuName'] = '商家管理';
            $crumbs['twoMenuName'] = '添加商品';

            $types = db('goods_type')->select();
            $business = db('saas_business')->where('status',1)->select();

            return $this->fetch('', compact('crumbs', 'types', 'business'));
        }
    }

    public function edit(Request $request)
    {
        if ($request->isPost()){
            $post = $request->post();

            $result = $this->validate($post, 'GoodsValidate');
            if($result !== true){
                $ajax['msg'] = $result;
                return json($ajax);
            }

            $data['goods_name'] = $post['goods_name'];
            $data['img'] = $post['img'];
            $data['type_id'] = $post['type_id'];
            $data['desc'] = $post['desc'];
            $data['b_id'] = $post['b_id'];
            $data['imgs'] = $post['imgs'];
            $data['id'] = $post['id'];

            Db::startTrans();
            $res = SaasGoods::update($data);
            if ($res !== false){

                // 简单粗暴方法 商品规格删除之后再添加
                $del_specs = db('saas_goods_specs')->where('goods_id', $data['id'])->delete();
                if ($del_specs !== false){

                    // 团购数量和规格 转 json
                    //$number_num_json = [];
                    $specsData = [];
                    foreach($post['t_price_number'] as $k1 => $str){

                        //$number_num_arr = [];
                        //$arr = explode('@', $str);
                        //foreach($arr as $k => $v){
                        //    //$ar = explode(',', $v);
                        //    //$number_num_arr[$ar[0]] = $ar[1];
                        //    $number_num_arr[$k+1] = $v;
                        //}
                        //$number_num_json[] = json_encode($number_num_arr);

                        // 存储商品规格数据
                        if ($post['is_group_buy'] == 2){
                            $specsData[] =
                                [
                                    'specs_name' => $post['specs_name'][$k1],
                                    'stock' => $post['stock'][$k1],
                                    //'t_price_number' => $number_num_json[$k1],
                                    't_price_number' => $str,
                                    'goods_id' => $data['id'],
                                ];
                        }else{
                            $specsData[] =
                                [
                                    'specs_name' => $post['specs_name'][$k1],
                                    'stock' => $post['stock'][$k1],
                                    'price' => $post['price'][$k1],
                                    //'t_price_number' => $number_num_json[$k1],
                                    't_price_number' => $str,
                                    'goods_id' => $data['id'],
                                ];
                        }
                    }

                    $addSpecs = db('saas_goods_specs')->insertAll($specsData);
                    if ($addSpecs){
                        Db::commit();
                        $ajax['code'] = 1;
                        $ajax['msg'] = '操作成功';
                        $ajax['url'] = url('/admin/goods');
                    }else{
                        Db::rollback();
                        $ajax['msg'] = '添加规格有误';
                    }
                }else{
                    Db::rollback();
                    $ajax['msg'] = '操作失败';
                }
            }else{
                $ajax['msg'] = '操作失败';
            }
            return json($ajax);
        }else{
            $crumbs['oneMenuName'] = '商家管理';
            $crumbs['twoMenuName'] = '修改商品';

            $id = input('id');

            $types = db('goods_type')->select();
            $business = db('saas_business')->where('status',1)->select();
            $data = db('saas_goods')->find($id);
            $specs = db('saas_goods_specs')->where('goods_id', $id)->select();

            //foreach($specs as $k => $v){
            //    //$jsonToArray = json_decode($v['t_price_number'], true);
            //    //foreach($jsonToArray as $k1 => $v1){
            //    //    $number_price_arr[] = $k1.','.$v1;
            //    //}
            //    //foreach($jsonToArray as $k1 => $v1){
            //    //    $number_price_arr[$k1-1] = $v1;
            //    //}
            //    //$arrayToStr = implode('@', $number_price_arr);
            //    unset($number_price_arr);
            //    $specs[$k]['t_price_number'] = $arrayToStr;
            //}

            return $this->fetch('add', compact('crumbs', 'types', 'business', 'data', 'id', 'specs'));
        }
    }

    public function close(Request $request)
    {
        if ($request->isPost())
        {
            $id = input('id');
            $save['id'] = $id;
            $save['status'] = 0;
            $res = SaasGoods::update($save);
            if($res !== false){
                $ajax['code'] = 1;
                $ajax['msg'] = '操作成功';
            }else{
                $ajax['msg'] = '操作失败';
            }
            return json($ajax);
        }
    }

    /**
     *  添加商品规格
     */
    public function addGoodsSpecs(Request $request)
    {
        return $this->fetch();
    }
}